package com.yanggu.jt808.model.req;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import com.yanggu.jt808.annotation.Jt808Property;
import com.yanggu.jt808.consts.Jt808Constant;
import com.yanggu.jt808.model.base.DataPackage;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 终端注册包
 *
 * @Description RegisterMsg
 * @Author guoyb
 * @Date 2023/11/6 15:23
 */
@Data
public class T0100Msg extends DataPackage {

    @Jt808Property(length = 2)
    private Short provinceId;//省域ID 2字节

    @Jt808Property(index = 2, length = 2)
    private Short cityId;//市县ID 2字节
    private String manufacturerId;//制造商ID 5字节
    private String terminalType;//终端型号 8字节
    private String terminalNumber;//终端ID，由制造商自己定义 7字节
    private int licensePlateColor;//车牌颜色 1字节-无符号单字节整形
    private String licensePlate;//车牌号 剩余字节

    public T0100Msg(DataPackage dataPackage) {
        super(dataPackage);
    }

    @Override
    public void parseBody() {

        byte[] bytes = toBytes();
        boolean version2019 = getHeader().isIfVersion2019();

        //解析终端注册的数据包

        Field[] fields = ReflectUtil.getFields(this.getClass());
        for (Field field : fields) {
            Jt808Property annotation = AnnotationUtil.getAnnotation(field, Jt808Property.class);
            if (Objects.nonNull(annotation)) {
                int length = annotation.length();
                int index = annotation.index();
            }

        }


        int provinceVal = parseIntFromBytes(bytes, 0, 2);
        this.setProvinceId((short) provinceVal);
        this.setCityId((short) parseIntFromBytes(bytes, 2, 2));

        // 制造商ID
        String manufacturerId = null;
        //终端型号
        String terminalType = null;
        //终端ID
        String terminalNumber = null;
        //车牌颜色
        int licenseColor = 0;
        //车牌
        String license = null;

        byte[] bytes1 = null;
        if (version2019) {
            manufacturerId = parseStringFromBytes(bytes, 4, 11);
            terminalType = parseStringFromBytes(bytes, 15, 30);
            terminalNumber = parseStringFromBytes(bytes, 45, 30);
            licenseColor = parseIntFromBytes(bytes, 75, 1);
            bytes1 = parseBytesFromBytes(bytes, 76, -1);
        } else {
            manufacturerId = parseStringFromBytes(bytes, 4, 5);
            terminalType = parseStringFromBytes(bytes, 9, 20);
            terminalNumber = parseStringFromBytes(bytes, 29, 7);
            licenseColor = parseIntFromBytes(bytes, 36, 1);
            bytes1 = parseBytesFromBytes(bytes, 37, -1);
        }
        this.setManufacturerId(manufacturerId);
        this.setTerminalType(terminalType);
        this.setTerminalNumber(terminalNumber);
        this.setLicensePlateColor(licenseColor);
        license = new String(bytes1, Jt808Constant.DEFAULT_CHARSET);
        this.setLicensePlate(license);

        // bo TODO 使用注解,解析字段


    }
}
